<template>
  <div class="keyholder" v-loading="loading">
    <div class="max-box">
      <div class="left">
        <div>keyHolder</div>
        <div v-for="(item,i) in dict.type.sys_on_watch_time_duration" :key="i">
          {{ item.label }}
        </div>
      </div>
      <div class="right">
        <div class="show-room">
          <div v-for="item in keyholderOptions" :key="item.staffId">
            {{ item.staffName }}
          </div>
        </div>
        <div v-for="(dict,i) in dict.type.sys_on_watch_time_duration" :key="i" class="user-list">
          <div v-for="(item,index) in keyHolderManageMap[dict.value]" :key="index" @click="handleUpdate(item)" @dblclick="item.occupy&&handleDelete(item)">
            {{ item.occupy ? item.showroomNo==='00'?'Flier':item.showroomNo : '' }}
          </div>
        </div>
      </div>
    </div>
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="84px">

        <el-form-item label="展厅名称" prop="showroomId">
          <el-select v-model="form.showroomId" placeholder="请选择展厅" @change="updateZoneId">
            <el-option
              v-for="showroom in showroomOptions"
              :key="showroom.showroomId"
              :label="showroom.showroomNo  +'区域：【'+ showroom.showroomName +'】'"
              :value="showroom.showroomId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="展厅区域" prop="showroomNo">
          <el-input v-model="form.showroomNo" placeholder="关联区域" label-width="28px"
                    class="custom-input-width"/>
        </el-form-item>


        <el-form-item label="KeyHolder" prop="keyholderId">
          <el-select v-model="form.keyholderId" placeholder="请选择KeyHolder">
            <el-option
              v-for="staff in keyholderOptions"
              :key="staff.staffId"
              :label="staff.staffName"
              :value="staff.staffId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="早晚班" prop="earlyLateWork">
          <el-select v-model="form.earlyLateWork" placeholder="请选择早晚班">
            <el-option
              v-for="dict in dict.type.sys_on_watch_type"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="值班时间" prop="onWatchTime">
          <el-date-picker clearable
                          v-model="form.onWatchTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择值班时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="时间段" prop="watchTimeDuration">
          <el-select v-model="form.watchTimeDuration" placeholder="请选择时间段">
            <el-option
              v-for="dict in dict.type.sys_on_watch_time_duration"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('vue.submit') }}</el-button>
        <el-button @click="cancel">{{ $t('vue.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { projectList, showroomList, listShowroom } from '@/api/system/showroom'
import { listProduct } from '@/api/system/productAll'
import { staffList } from '@/api/system/staff'
import { listKeyHolderManage, getKHManage, delKHManage, updateKHManage, addKHManage } from '@/api/system/keyholder'
import moment from 'moment'
import showroom from '@/views/system/showroom'

export default {
  name: 'elshift-bottom',
  dicts: ['sys_on_watch_type', 'sys_on_watch_time_duration'],
  data() {
    return {
      moment,
      // 遮罩层
      loading: false,
      keyHolderManageMap: [],
      showroomList: [],
      showroomFlier: [],
      showRoomIndex: [],
      showroomOptions: [],
      keyholderOptions: [],
      queryParams: {
        onWatchTime: moment('2024-03-10').format('YYYY-MM-DD')
      },
      form: {},
      rules: {},
      title: '',
      open: false,
      timeout: null
    }
  },
  methods: {
    handleDelete(row) {
      if(this.timeout){
        clearInterval(this.timeout)
        this.timeout = null
      }
      const ids = row.id;
      this.$modal.confirm('是否确认删除排班管理编号为"' + ids + '"的数据项？').then(function() {
        return delKHManage(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('vue.deleteSuccess'));
      }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateKHManage({...this.form}).then(response => {
              this.$modal.msgSuccess(this.$t('vue.editSuccess'));
              this.open = false;
              this.getList();
            });
          } else {
            addKHManage({...this.form}).then(response => {
              this.$modal.msgSuccess(this.$t('vue.addSuccess'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        earlyLateWork: null,
        watchTimeDuration: null,
        keyholderId: null,
        onWatchTime: null,
        createTime: null,
        updateTime: null,
        showroomNo: null
      };
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if(this.timeout){
        return
      }
      this.timeout = setInterval(()=> {
        if (this.timeout) {
          clearInterval(this.timeout)
          this.timeout = null
        }
        this.reset();
        const id = row.id
        if (id) {
          getKHManage(id).then(response => {
            this.form = response.data;
            this.open = true;
            this.title = "修改keyholder排班信息管理";
          });
        } else {
          this.form.keyholderId = row.keyholderId;
          this.form.watchTimeDyration = row.watchTimeDyration;
          this.form.onWatchTime = this.queryParams.onWatchTime
          this.open = true;
          this.title = "新增keyholder排班信息管理";
        }
      },200)
    },
    handleQuery(queryParams) {
      this.queryParams = queryParams || {}
      this.getList()
    },
    getShowroomList() {
      showroomList().then(response => {
        this.showroomOptions = response.data
      })
    },
    updateZoneId() {
      const selectedshowroomId = this.form.showroomId
      this.form.showroomNo = this.getShowroomNo(selectedshowroomId)
    },
    getShowroomNo(id) {
      if (this.showroomOptions && this.showroomOptions.length > 0) {
        let option = this.showroomOptions.find(option => Number(option.showroomId) === Number(id))
        return option ? option.showroomNo : ''
      }
      return ''
    },
    getKeyHolderList() {
      staffList('Keyholder').then(response => {
        this.keyholderOptions = response.data
        this.getList()
      })
    },
    getKeyHolder(id) {
      if (this.keyholderOptions && this.keyholderOptions.length > 0) {
        let option = this.keyholderOptions.find(option => option.staffId === id)
        return option ? option.staffName : ''
      }
      return ''
    },
    getList() {
      this.loading = true
      listKeyHolderManage(this.queryParams).then(response => {
        const map = {}
        const list = response.rows
        this.dict.type.sys_on_watch_time_duration.forEach((time) => {
          map[time.value] = []
          this.keyholderOptions.forEach(keyholder => {
            const data = list.find(d => d.keyholderId === keyholder.staffId && d.watchTimeDuration.toString() === time.value.toString())
            if (data) {
              map[time.value].push({ ...data, occupy: true })
            } else {
              map[time.value].push({
                keyholderId: keyholder.staffId,
                watchTimeDyration: time.value,
                occupy: false
              })
            }
          })
        })
        this.keyHolderManageMap = map
      }).finally(()=>{
        this.loading = false
      })
    }
  },
  mounted() {
    this.getShowroomList()
    this.getKeyHolderList()
  }
}
</script>

<style scoped lang="scss">
.keyholder{
  margin-top: 40px;
}
.max-box {
  display: flex;

  .left {
    width: 130px;

    > div {
      text-align: center;
      height: 30px;
      line-height: 30px;
      border-left: 1px solid #000;
      border-right: 1px solid #000;
      border-bottom: 1px solid #000;
      padding: 0 5px;

      &:first-child {
        border-top: 1px solid #000;
        background: rgba(101, 220, 236, 0.4);
      }
    }
  }

  .right {
    width: calc(100% - 130px);
    overflow-x: auto;

    .show-room {
      display: flex;

      > div {
        min-width: 130px;
        width: 130px;
        height: 30px;
        line-height: 30px;
        padding: 0 5px;
        border-bottom: 1px solid #000;
        border-top: 1px solid #000;
        border-right: 1px solid #000;
        background: rgba(101, 220, 236, 0.4);
        text-align: center;
      }
    }

    .region {
      display: flex;

      > div {
        width: 130px;
        height: 30px;
        line-height: 30px;
        padding: 0 5px;
        border-bottom: 1px solid #000;
        border-left: 1px solid #000;
        text-align: center;
        background: #ddd;

        &:last-child {
          border-right: 1px solid #000;
        }
      }
    }

    .user-list {
      display: flex;

      > div {
        min-width: 130px;
        width: 130px;
        height: 30px;
        line-height: 30px;
        padding: 0 5px;
        border-bottom: 1px solid #000;
        border-right: 1px solid #000;
        text-align: center;
        cursor: pointer;

        &:last-child {
          border-right: 1px solid #000;
        }
      }
    }
  }
}
</style>
